package com.chen.aspect;

import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
import com.alibaba.fastjson.JSON;
import com.chen.model.WebLog;
import com.chen.utils.IpUtils;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.LocalVariableTableParameterNameDiscoverer;
import org.springframework.core.annotation.Order;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.HashMap;

/**
 * @Author: chen
 * @Date: 2021/4/16 10:03 AM
 * @Version 1.0
 */
@Aspect
@Order(1)
@Component
@Slf4j
public class WebLogAspect {

    private static final String defDescription = "该方法没有描述";
    private static final String defUserName = "anonymous";


    @Pointcut("execution(* com.chen.controller.*.*(..))")
    public void setWebLogAspectPotcut() {

    }

    //ProceedingJoinPoint 这个是就代表目标方法
    @Around(value = "setWebLogAspectPotcut()")
    public Object aroundAdvice(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {

        WebLog webLog = new WebLog();

        MethodSignature signature = (MethodSignature) proceedingJoinPoint.getSignature();
        Method method = signature.getMethod();

        ApiOperation annotation = method.getAnnotation(ApiOperation.class);

        //设置方法的描述
        if (annotation == null) {
            webLog.setDescription(defDescription);
        } else {
            String value = annotation.value();
            webLog.setDescription(StringUtils.isBlank(value) ? defDescription : value);
        }

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        //设置用户
        webLog.setUsername(authentication == null ? defUserName : authentication.getPrincipal().toString());


        Object result = null;
        StopWatch stopWatch = new StopWatch(); // 创建计时器
        stopWatch.start(); //  开始计时器
        result = proceedingJoinPoint.proceed(proceedingJoinPoint.getArgs()); // 不需要我们自己处理这个异常
        stopWatch.stop(); // 记时结束

        //设置方法的消耗时间
        webLog.setSpendTime(stopWatch.getTotalTimeMillis());

        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();

        HttpServletRequest request = requestAttributes.getRequest();

        String requestURI = request.getRequestURI();
        String requestUrl = request.getRequestURL().toString();

        webLog.setBasePath(StrUtil.removeSuffix(requestUrl,
                URLUtil.url(requestUrl).getPath()));
        webLog.setUri(requestURI);
        webLog.setUrl(requestUrl);
        webLog.setMethod(request.getMethod());
        webLog.setIp(IpUtils.getIpAddr(request));
        webLog.setParameter(getMethodParameter(method, proceedingJoinPoint.getArgs()));
        webLog.setResult(result);

//        log.info(JSON.toJSONString(webLog,true));

        return result;

    }

    //    //获取参数
    public static Object getMethodParameter(Method method, Object[] args) {
        LocalVariableTableParameterNameDiscoverer
                localVariableTableParameterNameDiscoverer =
                new LocalVariableTableParameterNameDiscoverer();
        String[] parameterNames = localVariableTableParameterNameDiscoverer.getParameterNames(method);
        HashMap<String, Object> methodParameters = new HashMap<>();
        if (args != null) {
            for (int i = 0; i < parameterNames.length; i++) {
                if (parameterNames[i].equalsIgnoreCase("password") ||
                        parameterNames[i].equalsIgnoreCase("file")||
                        parameterNames[i].equalsIgnoreCase("response")) {
                    methodParameters.put(parameterNames[i], "受限制的参数类型");
                } else {
                    methodParameters.put(parameterNames[i], args[i] == null ? "" : JSON.toJSONString(args[i]));
                }
            }
        }
        return methodParameters;
    }

}
